﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace K9Nano.Updater.Utils;

internal static class JsonUtils
{
    public static readonly JsonSerializerOptions Options;

    static JsonUtils()
    {
        Options = new JsonSerializerOptions(JsonSerializerDefaults.General)
        {
            PropertyNameCaseInsensitive = true,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
        };

        Options.Converters.Add(new JsonStringEnumConverter());
    }

    public static T? Deserialize<T>(string json)
    {
        return JsonSerializer.Deserialize<T>(json, Options);
    }

    public static T? DeserializeFromFile<T>(string jsonFile)
    {
        using var reader = File.Open(jsonFile, FileMode.Open, FileAccess.Read, FileShare.Read);
        return JsonSerializer.Deserialize<T>(reader, Options);
    }

    public static async ValueTask<T?> DeserializeFromFileAsync<T>(string jsonFile)
    {
        using var reader = File.Open(jsonFile, FileMode.Open, FileAccess.Read, FileShare.Read);
        return await JsonSerializer.DeserializeAsync<T>(reader, Options);
    }

    public static async ValueTask SaveAsync<T>(T data, string targetFile, bool writeIndented = true)
    {
        var options = writeIndented ? new JsonSerializerOptions(Options) { WriteIndented = true } : Options;
        var bytes = JsonSerializer.SerializeToUtf8Bytes<T>(data, options);
        await File.WriteAllBytesAsync(targetFile, bytes);
    }
}